﻿using MahApps.Metro.Controls;
using SQX.ViewModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using SQX.DataModel;
using System.Windows.Threading;
using System.Windows.Controls.Primitives;

namespace SQX.Views
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : MetroWindow
    {
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = new MainWindowViewModel();
            (this.DataContext as MainWindowViewModel).ThreadStatus = MainWindowViewModel.ActiveThreadStatus.Idle;
        }

        private async void newMDXQuery_Click(object sender, RoutedEventArgs e)
        {
            Connection conWnd = new Connection(Service.SourceType.SourceOLAP);
            conWnd.ShowDialog();
            var model = (this.DataContext as MainWindowViewModel);
            if ((conWnd.DataContext as ConnectionViewModel).ActionResult && (conWnd.DataContext as ConnectionViewModel).ServerName != ""
                && (conWnd.DataContext as ConnectionViewModel).DatabaseName != "")
            {
                if (model.ActiveModel == null | (model.FindModel("CubeViewModel") == null))
                {
                    model.ThreadStatus = MainWindowViewModel.ActiveThreadStatus.Running;
                    CubeViewModel vm = new CubeViewModel(
                                                            (conWnd.DataContext as ConnectionViewModel).ServerName,
                                                            (conWnd.DataContext as ConnectionViewModel).DatabaseName,
                                                            (conWnd.DataContext as ConnectionViewModel).CatalogName
                                                         );
                    await vm.InitializeModelAsync();
                    if (vm.ExceptionMessage == "")
                    {
                        model.ActiveModel = vm;
                        model.ModelCollection.Add(vm);
                    }
                    if ((this.DataContext as MainWindowViewModel).ThreadStatus == MainWindowViewModel.ActiveThreadStatus.Running)
                    {
                        (this.DataContext as MainWindowViewModel).ThreadStatus = MainWindowViewModel.ActiveThreadStatus.Idle;
                    }
                }
                    // model not null, query not null - just add new query in same context if it is MDX query
                else if (model.ActiveModel.ActiveQuery.QueryType == Service.SourceType.SourceOLAP)
                {
                    var box = (RichTextBox)Service.GetElementFromTabItemTemplate(this.queries,
                                                                                 this.queries.ItemContainerGenerator,
                                                                                 this.queries.SelectedContent,
                                                                                 "queryEditor");
                    box.SelectAll();
                    model.ActiveModel.ActiveQuery.Text = box.Selection.Text;
                    model.ActiveModel.AddQuery("", Service.SourceType.SourceOLAP, (conWnd.DataContext as ConnectionViewModel).ConnectionObject);
                    box.Selection.Text = "";
                }
                    // if current query is not olap query - try find same type of queryModel in collection
                else
                {
                    var box = (RichTextBox)Service.GetElementFromTabItemTemplate(this.queries,
                                                                                 this.queries.ItemContainerGenerator,
                                                                                 this.queries.SelectedContent,
                                                                                 "queryEditor");
                    box.SelectAll();

                    var queryModel = model.FindModel("CubeViewModel");
                    model.ActiveModel.ActiveQuery.Text = box.Selection.Text;
                    model.ActiveModel = queryModel;
                    model.ActiveModel.AddQuery("", Service.SourceType.SourceOLAP, (conWnd.DataContext as ConnectionViewModel).ConnectionObject);
                    box.Selection.Text = "";
                }
            }
        }

        private async void queries_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // query text is not bound due to performance issues with attached DP, so we need to manually transfer text if change occur
            // acutally we don't need that hard text binding, cause it is used only in 2 cases - query run event and query tab change event
            if (this.queries.Items.Count > 1 && this.queries.SelectedContent != null)
            {
                var box = (RichTextBox)Service.GetElementFromTabItemTemplate(this.queries,
                    this.queries.ItemContainerGenerator,
                    this.queries.SelectedContent,
                    "queryEditor");              
                box.SelectAll();
                if (e.AddedItems.Count > 0 && e.AddedItems[0].GetType().Name.Contains("Query"))
                {
                    // add text to prev. query
                    if (e.RemovedItems.Count > 0 && e.RemovedItems[0].GetType().Name.Contains("Query")) (e.RemovedItems[0] as Query).Text = box.Selection.Text;
                    
                    // re-insert query text
                    box.Selection.Text = (this.queries.DataContext as QueryViewModelBasic).ActiveQuery.Text;    
                
                    // re-apply formatting
                    TextRange documentRange = new TextRange(box.Document.ContentStart,
                                                       box.Document.ContentEnd);

                    await this.Dispatcher.BeginInvoke(
                                                DispatcherPriority.Send, // fix lags, prioritize over rendering
                                                new Action(() => (this.queries.DataContext as QueryViewModelBasic).Markup.TryColorSyntax(box, queryEditor_TextChanged, documentRange))
                                           );
                }
            }
        }

        private async void runQuery_Click(object sender, RoutedEventArgs e)
        {
            if (this.queries.DataContext != null)
            {
                var model = (this.DataContext as MainWindowViewModel);
                var box = (RichTextBox)Service.GetElementFromTabItemTemplate(this.queries,
                    this.queries.ItemContainerGenerator,
                    this.queries.SelectedContent,
                    "queryEditor");
                if ((this.queries.DataContext as QueryViewModelBasic).ActiveQuery != null)
                {
                    // get query text
                    model.ActiveModel.ActiveQuery.Text = Service.GetQueryText(box);

                    (this.DataContext as MainWindowViewModel).ThreadStatus = MainWindowViewModel.ActiveThreadStatus.Running;
                    (this.DataContext as MainWindowViewModel).RunQueryTimer();

                    await (this.queries.DataContext as QueryViewModelBasic).ActiveQuery.RunQueryAsync();

                    (this.DataContext as MainWindowViewModel).StopQueryTimer();
                    (this.DataContext as MainWindowViewModel).ThreadStatus = MainWindowViewModel.ActiveThreadStatus.Idle;
                }
            }
        }

        private async void queryEditor_PreviewKeyUp(object sender, KeyEventArgs e)
        {
            var model = (this.DataContext as MainWindowViewModel);
            // set box
            var box = (sender as RichTextBox);

            // set popup
            var popup = (this.Resources["QueryHelp"] as Popup);

            // exec if needed
            if (e.Key == Key.F5)
            {
                if (this.queries.DataContext != null)
                {
                    // get query text
                    model.ActiveModel.ActiveQuery.Text = Service.GetQueryText(box);

                    // initate query timer
                    model.ThreadStatus = MainWindowViewModel.ActiveThreadStatus.Running;
                    model.RunQueryTimer();

                    // await execution
                    await (this.queries.DataContext as QueryViewModelBasic).ActiveQuery.RunQueryAsync();

                    model.StopQueryTimer();
                    model.ThreadStatus = MainWindowViewModel.ActiveThreadStatus.Idle;
                }
            }

            else if (popup.IsOpen && (e.Key == Key.Up | e.Key == Key.Down))
            {
                (popup.Child as ListBox).Focus();
            }
            else if (popup.IsOpen && (e.Key == Key.Escape | e.Key == Key.Enter))
            {
                popup.IsOpen = false;
            }

            else if (!popup.IsOpen && (e.Key != Key.F5 &
                                       e.Key != Key.Up &
                                       e.Key != Key.Down &
                                       e.Key != Key.Enter &
                                       e.Key != Key.Tab &
                                       e.Key != Key.Space &
                                       e.Key != Key.Back &
                                       e.Key != Key.CapsLock &
                e.Key != Key.LeftShift &
                e.Key != Key.RightShift &
                e.Key != Key.Right &
                e.Key != Key.Left &
                                       !Service.IgnoredSymbols.Contains(model.InputSymbol)))
            {
                 // extreme slowdown here, fixes : add async call via dispatcher
            // defer update by X millis
            var current = box.CaretPosition;
            var currentBlock = box.Document.Blocks.Where(x => x.ContentStart.CompareTo(current) == -1 && x.ContentEnd.CompareTo(current) == 1).FirstOrDefault();
                if (currentBlock != null)
                {
                    var range = new TextRange(currentBlock.ContentStart, currentBlock.ContentEnd);
                    model.CurrentRange = range;
                    var text = range.Text;

                    if (!popup.IsOpen)
                    {
                        await box.Dispatcher.BeginInvoke(DispatcherPriority.Send,
                                                          new Action(() => ShowHelpPopup(box.CaretPosition.GetCharacterRect(LogicalDirection.Forward), box))
                                                        );
                    }

                }
            }
            else if (popup.IsOpen && (e.Key != Key.F5 &
                                       e.Key != Key.Up &
                                       e.Key != Key.Down &
                                       e.Key != Key.Enter &
                                       e.Key != Key.Tab &
                                       e.Key != Key.Space &
                                       e.Key != Key.Back &
                                       e.Key != Key.CapsLock &
                                       e.Key != Key.LeftShift &
                                       e.Key != Key.RightShift &
                                       e.Key != Key.Right &
                                       e.Key != Key.Left &
                                       !Service.IgnoredSymbols.Contains(model.InputSymbol)))
            {
                if ((this.DataContext as ViewModelBasic).DeferredAct == null)
                {
                    (this.DataContext as ViewModelBasic).DeferredAct = DeferredAction.Create(new Action(async () =>
                        await popup.Dispatcher.BeginInvoke(
                                                    DispatcherPriority.Send,
                                                    new Action(
                                                                () => ((popup.Child as ListBox).ItemsSource as CollectionView).Refresh()
                                                              )
                                                          )
                        ));
                }
                else
                {
                    (this.DataContext as ViewModelBasic).DeferredAct.Defer(new TimeSpan(0, 0, 0, 0, 250));
                    if (((popup.Child as ListBox).ItemsSource as CollectionView).IsEmpty) popup.IsOpen = false;
                }

            } 

           
        }

        private async void stopQuery_Click(object sender, RoutedEventArgs e)
        {
            await (this.DataContext as MainWindowViewModel).ActiveModel.ActiveQuery.StopQueryAsync();
        }

        private void querySaver_Click(object sender, RoutedEventArgs e)
        {
            var box = (RichTextBox)Service.GetElementFromTabItemTemplate(this.queries,
                this.queries.ItemContainerGenerator,
                this.queries.SelectedContent,
                "queryEditor");
            (this.DataContext as MainWindowViewModel).ActiveModel.ActiveQuery.Text = Service.GetQueryText(box);
            (this.DataContext as MainWindowViewModel).SaveActiveQuery();
        }

        private async void newSQLQuery_Click(object sender, RoutedEventArgs e)
        {
            Connection conWnd = new Connection(Service.SourceType.SourceSQL);
            conWnd.ShowDialog();
            var model = (this.DataContext as MainWindowViewModel);
            if ((conWnd.DataContext as ConnectionViewModel).ActionResult && (conWnd.DataContext as ConnectionViewModel).ServerName != ""
                && (conWnd.DataContext as ConnectionViewModel).DatabaseName != "")
            {
                if (model.ActiveModel == null | (model.FindModel("SQLViewModel") == null))
                {
                    model.ThreadStatus = MainWindowViewModel.ActiveThreadStatus.Running;
                    SQLViewModel sqlvm = new SQLViewModel(
                                                            (conWnd.DataContext as ConnectionViewModel).ServerName,
                                                            (conWnd.DataContext as ConnectionViewModel).DatabaseName
                                                         );
                    await sqlvm.InitializeModelAsync();
                    if (sqlvm.ExceptionMessage == "")
                    {
                        model.ActiveModel = sqlvm;
                        model.ModelCollection.Add(sqlvm);
                    }
                    if (model.ThreadStatus == MainWindowViewModel.ActiveThreadStatus.Running)
                    {
                        model.ThreadStatus = MainWindowViewModel.ActiveThreadStatus.Idle;
                    }
                }
                else if (model.ActiveModel.ActiveQuery.QueryType == Service.SourceType.SourceSQL)
                {
                    var box = (RichTextBox)Service.GetElementFromTabItemTemplate(this.queries,
                                                                                 this.queries.ItemContainerGenerator,
                                                                                 this.queries.SelectedContent,
                                                                                 "queryEditor");
                    box.SelectAll();
                    model.ActiveModel.ActiveQuery.Text = box.Selection.Text;
                    model.ActiveModel.AddQuery("", Service.SourceType.SourceSQL, (conWnd.DataContext as ConnectionViewModel).ConnectionObject);
                    box.Selection.Text = "";
                }

                else
                {
                    var box = (RichTextBox)Service.GetElementFromTabItemTemplate(this.queries,
                                                                                 this.queries.ItemContainerGenerator,
                                                                                 this.queries.SelectedContent,
                                                                                 "queryEditor");
                    box.SelectAll();

                    var queryModel = model.FindModel("SQLViewModel");
                    model.ActiveModel.ActiveQuery.Text = box.Selection.Text;
                    model.ActiveModel = queryModel;
                    model.ActiveModel.AddQuery("", Service.SourceType.SourceSQL, (conWnd.DataContext as ConnectionViewModel).ConnectionObject);
                    box.Selection.Text = "";
                }
            }
        }

        private async void queryEditor_TextChanged(object sender, TextChangedEventArgs e)
        {
            // set query status to not-saved
            (this.DataContext as MainWindowViewModel).ActiveModel.ActiveQuery.IsSaved = false;
            TextRange t = null;
            var box = (sender as RichTextBox);

            // rescan document if inserted
            if (e.Changes.Count > 0 && e.Changes.ToList()[0].AddedLength > 100)
            {
                TextRange documentRange = new TextRange(box.Document.ContentStart,
                                                        box.Document.ContentEnd);
                await this.Dispatcher.BeginInvoke(
                                                DispatcherPriority.Send, // fix lags, prioritize over rendering
                                                new Action(() => (this.queries.DataContext as QueryViewModelBasic).Markup.TryColorSyntax(box, queryEditor_TextChanged, documentRange))
                                           );

            }
            else
            {
                if (box.Document != null && box.Document.Blocks.Count > 0)
                {
                    TextPointer current = box.CaretPosition;

                    // get current block
                    var currentBlock = box.Document.Blocks.Where(x => x.ContentStart.CompareTo(current) == -1 && x.ContentEnd.CompareTo(current) == 1).FirstOrDefault();
                    if (currentBlock != null)
                    {
                        t = new TextRange(currentBlock.ContentStart, currentBlock.ContentEnd);
                        t.ClearAllProperties();
                        await this.Dispatcher.BeginInvoke(
                                                        DispatcherPriority.Send, // fix lags, prioritize over rendering
                                                        new Action(() => (this.queries.DataContext as QueryViewModelBasic).Markup.TryColorSyntax((sender as RichTextBox), queryEditor_TextChanged, t))
                                                   ); 
                    }
                }
            }
        }

       private void ShowHelpPopup(Rect placement, RichTextBox box)
        {
            var popup = (this.Resources["QueryHelp"] as Popup);
            popup.PlacementTarget = box;
            var shifted_placement = new Rect(placement.X - 10, placement.Y + 5, placement.Width, placement.Height);
            popup.PlacementRectangle = shifted_placement;
            popup.IsOpen = true;
            (popup.Child as ListBox).SelectedIndex = 0; 
        }
        
       private void CollectionViewSource_Filter(object sender, FilterEventArgs e)
       {
           if ((this.DataContext as MainWindowViewModel).CurrentRange != null)
           {
               var text = (this.DataContext as MainWindowViewModel).CurrentRange.Text;

               if (text != "" && (text.Contains('[')))
               {
                   var index = text.LastIndexOf('[');
                   text = text.Substring(index, text.Length - index).Replace('\r', ' ').Replace('\n', ' ').Trim();

                   if ((e.Item as LanguageObject).ObjectName.ToLower().Contains(text.ToLower())) e.Accepted = true;
                   else e.Accepted = false;
               }
               else if (text != "" && char.IsUpper(text[0]))
               {
                   text = text.Replace('\r', ' ').Replace('\n', ' ').Trim();

                   if ((e.Item as LanguageObject).ObjectName.ToLower().Contains(text.ToLower())) e.Accepted = true;
                   else e.Accepted = false;
               }

           }
       }

       private void hintsSelector_KeyDown(object sender, KeyEventArgs e)
       {
           var popup = (this.Resources["QueryHelp"] as Popup);
           var rbox = (popup.PlacementTarget as RichTextBox);

           // restore caret
           rbox.CaretPosition = (this.DataContext as MainWindowViewModel).CurrentPosition;

           if (e.Key != Key.Down & e.Key != Key.Up & e.Key != Key.Escape & e.Key != Key.Enter)
           {
               (((sender as ListBox).Parent as Popup).PlacementTarget as RichTextBox).Focus();
           }
           else 
           {
               switch (e.Key)
               {
                   case Key.Enter:
                       popup.IsOpen = false;
                       var box = (sender as ListBox);
                       if (box != null && box.SelectedItem != null)
                       {
                           var text = Service.FindLastWord(rbox);                          
                           var found = (box.SelectedItem as LanguageObject).ObjectName.ToLower();

                           if (text != "") rbox.CaretPosition.InsertTextInRun(found.Replace(text.ToLower(), ""));
                           else rbox.CaretPosition.InsertTextInRun(found);
                           rbox.CaretPosition = rbox.CaretPosition.GetPositionAtOffset(rbox.CaretPosition.GetTextRunLength(LogicalDirection.Forward),LogicalDirection.Forward);
                           rbox.Focus();
                       }
                       break;
                   case Key.Escape:

                       popup.IsOpen = false;
                       rbox.Focus();
                       break;
               }
           }
       }

       private void objExplorer_MouseMove(object sender, MouseEventArgs e)
       {
           //base.OnMouseMove(e);
           //if (e.LeftButton == MouseButtonState.Pressed)
           //{
           //    // Package the data.
           //    DataObject data = new DataObject();
           //    data.SetData(DataFormats.StringFormat, (sender as TreeViewItem).Header);
           //    data.SetData("Object", sender);

           //    // Inititate the drag-and-drop operation.
           //    DragDrop.DoDragDrop(this, data, DragDropEffects.Copy | DragDropEffects.Move);
           //}
       }

       private async void openQuery_Click(object sender, RoutedEventArgs e)
       {
           var model = (this.DataContext as MainWindowViewModel);
           System.Windows.Forms.OpenFileDialog openDlg = new System.Windows.Forms.OpenFileDialog();
           openDlg.Filter = "MDX File (*.mdx)|*.mdx|SQL File (*.sql)|*.sql|Text file (*.txt)|*.txt";
           openDlg.Title = "Open analytical query...";
           openDlg.ShowDialog();
           if (openDlg.FileName != "" && openDlg.CheckFileExists)
           {
               var ext = openDlg.FileName.Substring(openDlg.FileName.LastIndexOf('.'),openDlg.FileName.Length - openDlg.FileName.LastIndexOf('.'));
               if (ext == ".mdx")
               {
                   string fileContent = "";
                   // read file content
                   using (StreamReader sr = File.OpenText(openDlg.FileName))
                   {
                       fileContent = sr.ReadToEnd();
                   }
                   Connection conWnd = new Connection(Service.SourceType.SourceOLAP);
                   conWnd.ShowDialog();
                   if (model.ActiveModel != null)
                   {
                       model.ActiveModel.AddQuery(fileContent, Service.SourceType.SourceOLAP, (conWnd.DataContext as ConnectionViewModel).ConnectionObject);
                   }
                   else
                   {
                       model.ThreadStatus = MainWindowViewModel.ActiveThreadStatus.Running;
                       CubeViewModel vm = new CubeViewModel(
                                                               (conWnd.DataContext as ConnectionViewModel).ServerName,
                                                               (conWnd.DataContext as ConnectionViewModel).DatabaseName,
                                                               (conWnd.DataContext as ConnectionViewModel).CatalogName,
                                                               fileContent
                                                            );
                       await vm.InitializeModelAsync();
                       if (vm.ExceptionMessage == "")
                       {
                           model.ActiveModel = vm;
                           model.ModelCollection.Add(vm);
                       }
                       if ((this.DataContext as MainWindowViewModel).ThreadStatus == MainWindowViewModel.ActiveThreadStatus.Running)
                       {
                           (this.DataContext as MainWindowViewModel).ThreadStatus = MainWindowViewModel.ActiveThreadStatus.Idle;
                       }
                   }
               }
               else if (ext == ".sql")
               {

               }
           }
       }

        // Routed commands
       private void ExecuteRTBUndo(object sender, ExecutedRoutedEventArgs e)
       {
           (sender as RichTextBox).Undo();
       }

       private void ExecuteQuerySave(object sender, ExecutedRoutedEventArgs e)
       {
           var box = (RichTextBox)Service.GetElementFromTabItemTemplate(this.queries,
                this.queries.ItemContainerGenerator,
                this.queries.SelectedContent,
                "queryEditor");
           (this.DataContext as MainWindowViewModel).ActiveModel.ActiveQuery.Text = Service.GetQueryText(box);
           (this.DataContext as MainWindowViewModel).SaveActiveQuery();
       }

       private void queryEditor_Loaded(object sender, RoutedEventArgs e)
       {
           (sender as RichTextBox).AppendText((this.DataContext as MainWindowViewModel).ActiveModel.ActiveQuery.Text);
       }

       private void saveQuery_Click(object sender, RoutedEventArgs e)
       {
           if ((this.DataContext as MainWindowViewModel).ActiveModel != null)
           {
               var box = (RichTextBox)Service.GetElementFromTabItemTemplate(this.queries,
                    this.queries.ItemContainerGenerator,
                    this.queries.SelectedContent,
                    "queryEditor");
               (this.DataContext as MainWindowViewModel).ActiveModel.ActiveQuery.Text = Service.GetQueryText(box);
               (this.DataContext as MainWindowViewModel).SaveActiveQuery();
           }
       }

       private void queryEditor_PreviewKeyDown(object sender, KeyEventArgs e)
       {
           (this.DataContext as MainWindowViewModel).CurrentPosition = (sender as RichTextBox).CaretPosition;
       }

       private void queryEditor_PreviewTextInput(object sender, TextCompositionEventArgs e)
       {
           (this.DataContext as MainWindowViewModel).InputSymbol = e.Text;
       }

       private void models_DropDownOpened(object sender, EventArgs e)
       {
           var box = (RichTextBox)Service.GetElementFromTabItemTemplate(this.queries,
                this.queries.ItemContainerGenerator,
                this.queries.SelectedContent,
                "queryEditor");
           (this.DataContext as MainWindowViewModel).ActiveModel.ActiveQuery.Text = Service.GetQueryText(box);
       }

       private void settings_Click(object sender, RoutedEventArgs e)
       {
           
       }

       private void accentSwitcher_Click(object sender, RoutedEventArgs e)
       {
           (this.DataContext as MainWindowViewModel).NextAccent();
       }

       private void models_DropDownClosed(object sender, EventArgs e)
       {
           var box = (RichTextBox)Service.GetElementFromTabItemTemplate(this.queries,
                this.queries.ItemContainerGenerator,
                this.queries.SelectedContent,
                "queryEditor");
           box.SelectAll();
           box.Selection.Text = (this.DataContext as MainWindowViewModel).ActiveModel.ActiveQuery.Text;
       }

        // used to quickly add tree item desc. code to clipboard
       private void objExplorer_PreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e)
       {
           if ((sender as TreeView).SelectedItem != null)
           {
               Clipboard.SetText(((sender as TreeView).SelectedItem as SqxObject).ObjectCode);
           }
       }

       private void hintsSelector_MouseDoubleClick(object sender, MouseButtonEventArgs e)
       {
           var popup = (this.Resources["QueryHelp"] as Popup);
           var rbox = (popup.PlacementTarget as RichTextBox);

           // restore caret
           rbox.CaretPosition = (this.DataContext as MainWindowViewModel).CurrentPosition;
           popup.IsOpen = false;
           var box = (sender as ListBox);
           if (box != null && box.SelectedItem != null)
           {
               var text = Service.FindLastWord(rbox);
               var found = (box.SelectedItem as LanguageObject).ObjectName.ToLower();

               if (text != "") rbox.CaretPosition.InsertTextInRun(found.Replace(text, ""));
               else rbox.CaretPosition.InsertTextInRun(found);
               rbox.CaretPosition = rbox.CaretPosition.GetPositionAtOffset(rbox.CaretPosition.GetTextRunLength(LogicalDirection.Forward), LogicalDirection.Forward);
               rbox.Focus();
           }
   
       }

       private void queryCloser_Click(object sender, RoutedEventArgs e)
       {
           (this.DataContext as MainWindowViewModel).ActiveModel.QueryCollection.Remove((this.DataContext as MainWindowViewModel).ActiveModel.ActiveQuery);
           if ((this.DataContext as MainWindowViewModel).ActiveModel.QueryCollection.Count > 0)
           {
               (this.DataContext as MainWindowViewModel).ActiveModel.ActiveQuery = (this.DataContext as MainWindowViewModel).ActiveModel.QueryCollection[0];
           }
               // dispose model if no queries present
           else
           {
               (this.DataContext as MainWindowViewModel).ActiveModel.Dispose();
               (this.DataContext as MainWindowViewModel).ActiveModel = null;
           }
       }

    }
}
